package cn.yotta.user.core.server.iface.common.impl;

import cn.yotta.user.core.server.iface.common.CaptchaGenerator;
import cn.yotta.user.core.server.iface.common.CaptchaStorageStrategy;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wyaoyao
 * @date 2022/11/9 16:26
 * 内存存储
 */
public class InMemoryCaptchaStorageStrategy implements CaptchaStorageStrategy {

    private final Cache<String, CaptchaGenerator.Captcha> captchaCache;

    public InMemoryCaptchaStorageStrategy(Integer expireTime, TimeUnit timeUnit) {
        this.captchaCache = CacheBuilder.newBuilder()
                .expireAfterWrite(expireTime, timeUnit)
                .build();
    }

    @Override
    public String save(CaptchaGenerator.Captcha captcha) {
        final String token = UUID.randomUUID().toString();
        captchaCache.put(token, captcha);
        return token;
    }

    @Override
    public CaptchaGenerator.Captcha get(String token) {
        return captchaCache.getIfPresent(token);
    }

}
